package initialize

import (
	"time"
	"uploadSvc/config"
	"uploadSvc/global"
	"uploadSvc/initialize/internal"

	dm "github.com/nfjBill/gorm-driver-dm"
	"gorm.io/gorm"
)

// GormDM 初始化DM数据库
func GormDM() *gorm.DB {
	m := global.NS_CONFIG.DM
	if m.Dbname == "" {
		return nil
	}
	if db, err := gorm.Open(dm.Open(m.Dsn()), internal.Gorm.Config()); err != nil {
		return nil
	} else {
		sqlDB, _ := db.DB()
		sqlDB.SetMaxIdleConns(m.MaxIdleConns)
		sqlDB.SetMaxOpenConns(m.MaxOpenConns)
		sqlDB.SetConnMaxLifetime(5 * 60 * time.Second)
		return db
	}
}

// GormDMByConfig 初始化DM数据库用过传入配置
func GormDMByConfig(m config.DM) *gorm.DB {
	if m.Dbname == "" {
		return nil
	}
	if db, err := gorm.Open(dm.Open(m.Dsn()), internal.Gorm.Config()); err != nil {
		panic(err)
	} else {
		sqlDB, _ := db.DB()
		sqlDB.SetMaxIdleConns(m.MaxIdleConns)
		sqlDB.SetMaxOpenConns(m.MaxOpenConns)
		sqlDB.SetConnMaxLifetime(5 * 60 * time.Second)
		return db
	}
}
